import { Button, Form, message, Spin, Tabs } from 'antd';
import { WorkflowSwitchContext } from '../common';
import { WorkflowNodesView } from './WorkflowNodesView';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useMemo, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import Cls from 'classnames';
import { WorkflowNodesImage } from './WorkflowNodesImage';
import { SwapOutlined } from '@ant-design/icons';
import { WorkflowSwitchAPI } from '../common/type';
import '../common/styles.less';
import { getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { HandleFlowStateCommon, startProcessService } from '../services';

export const WorkflowSwitchModal: React.FC<WorkflowSwitchAPI.IWorkflowSwitchModal> = ({
  openVisible, //是否打开
  orderType, //业务类别
  category, // 总 流程类别
  businessCategory, // 相关业务 的流程类别
  requestController, //后端业务 Controller
  businessInfoObj, //选中的行数据
  selectFlowID, //选中的非默认流程id
  reloadInfoCallback, //发起流程后刷新管理页回调
  onClose, //关闭当前组件
  openFlowChangeModal, //打开切换非默认流程 modal
}) => {
  /**
   * 样式根节点
   */
  const prefixCls: string = 'workflow-switchroot-';

  /**
   * 流程节点ref
   */
  const workflowNodeRef = useRef<any>();

  /**
   * modal ref
   */
  const WorkflowModalRef: Ref<IOneModalRef> = useRef(null);

  /**
   * 关闭弹窗
   */
  const onCloseModal = () => {
    if (WorkflowModalRef) {
      if (WorkflowModalRef.current) {
        if (WorkflowModalRef.current.onModalCancel) {
          WorkflowModalRef.current.onModalCancel();
        }
      }
    }
  };

  /**
   * 保存当前流程id
   */
  const [saveProcessID, setSaveProcessID] = useState<string>(selectFlowID);

  /**
   * 表单实例
   */
  const [WorkflowSwitchForm] = Form.useForm();

  /**
   *  开启流程回调
   * @param res
   */
  const startProcessCallBack = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModal();
      reloadInfoCallback();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入发起流程
   */
  const { startProcessRun, startProcessLoading } = startProcessService(startProcessCallBack, requestController);

  /**
   * 发起审批流程
   */
  const onOk = () => {
    WorkflowSwitchForm?.validateFields()?.then((formData: any) => {
      const workFlowNodes: Record<string, any>[] = workflowNodeRef?.current?.workflowNodesList;
      let paramObject: Record<string, any>[] = []; //存储节点中的数据

      workFlowNodes?.forEach((itemNode: any, nodeIndex: number) => {
        let dealPostList: string[] = []; //存储办理岗位 id
        let postUserIDlist: string[] = []; //存储历史  岗位|人 id
        let dealUserList: string[] = []; //存储办理人 id

        // 遍历节点中所有的岗位节点
        itemNode?.postValues?.forEach((itemChild: any, childIndex: number) => {
          if (formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']']) {
            dealPostList?.push(`${formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']']}`);
          }
          if (
            formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']'] &&
            formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']
          ) {
            postUserIDlist?.push(
              `${formData['paramObject[' + nodeIndex + '].dealPositionID[' + childIndex + ']']}|${
                formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']
              }`,
            );
          }

          if (formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']) {
            dealUserList?.push(`${formData['paramObject[' + nodeIndex + '].dealerID[' + childIndex + ']']}`);
          }
        });
        paramObject.push({
          dealPositionID: dealPostList?.length > 0 ? dealPostList?.toString() : null,
          postDealerID: postUserIDlist?.length > 0 ? postUserIDlist?.toString() : null,
          dealerID: dealUserList?.length > 0 ? dealUserList?.toString() : null,
          taskIsSign: formData['paramObject[' + nodeIndex + '].taskIsSign'],
          seq: formData['paramObject[' + nodeIndex + '].seq'],
          procDefID: formData['paramObject[' + nodeIndex + '].procDefID'],
          orderID: formData['paramObject[' + nodeIndex + '].orderID'],
          taskNode: formData['paramObject[' + nodeIndex + '].taskNode'],
          dealerNum: formData['paramObject[' + nodeIndex + '].dealerNum'],
          taskName: formData['paramObject[' + nodeIndex + '].taskName'],
        });
      });

      /**
       * 处理状态之间的转变
       */
      const stateObj: Record<string, any> = HandleFlowStateCommon(businessInfoObj?.state, orderType);

      const params: Record<string, any> = {
        paramObject: paramObject,
        procDefID: saveProcessID,
        workflowType: category,
        orderType,
        createDepartmentID: businessInfoObj?.createDepartmentID,
        createPositionID: businessInfoObj?.createPositionID,
        createrID: businessInfoObj?.createrID,
        checkState: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000`,
        ...stateObj,
        id: businessInfoObj?.id,
        versionNum: businessInfoObj?.versionNum,
      };

      startProcessRun(params);
    });
  };

  /**
   * 处理Tabs页面
   */
  const tabsPaneItems = useMemo(() => {
    return [
      {
        label: '流程节点设置',
        key: 'ProcessNodeSettings',
        children: (
          <WorkflowNodesView
            switchFlowObj={{ processID: selectFlowID }}
            changeProcessID={setSaveProcessID}
            ref={workflowNodeRef}
          />
        ),
      },
      {
        label: '流程图',
        key: 'ProcessNodeChrat',
        children: <WorkflowNodesImage workflowID={saveProcessID} />,
      },
    ];
  }, [WorkflowSwitchForm, saveProcessID, workflowNodeRef]);

  return (
    <WorkflowSwitchContext.Provider
      value={{
        prefixCls,
        openVisible, //是否打开
        orderType, //业务类别
        category, // 相关业务 的流程类别
        businessCategory, // 总 流程类别
        requestController,
        reloadInfoCallback,
        businessInfoObj,
        onClose,
        nodeFlowForm: WorkflowSwitchForm,
      }}
    >
      <OneModal
        open={true}
        // getContainer={false}
        ref={WorkflowModalRef}
        title={'发起审批'}
        width={document.body.clientWidth * 0.6}
        bodyStyle={{
          padding: '0px',
        }}
        centered
        onCancel={onClose}
        footer={
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <div>
              <Button
                type={'primary'}
                icon={<SwapOutlined />}
                onClick={() => {
                  onCloseModal();
                  openFlowChangeModal(true);
                }}
              >
                使用非默认流程
              </Button>
            </div>
            <div>
              <Button
                onClick={() => {
                  onCloseModal();
                }}
              >
                取消
              </Button>
              <Button type={'primary'} onClick={onOk} loading={startProcessLoading}>
                确定
              </Button>
            </div>
          </div>
        }
      >
        <Spin spinning={startProcessLoading}>
          <Form form={WorkflowSwitchForm} className={prefixCls + 'workflowFormBox'}>
            <Tabs className={Cls(pageStyles['commonTabs'], prefixCls + 'workflowTabsBox')} type="card" items={tabsPaneItems} />
          </Form>
        </Spin>
      </OneModal>
    </WorkflowSwitchContext.Provider>
  );
};
